package mamikeji.liaowa.ui.activity.circle;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import jp.wasabeef.glide.transformations.BlurTransformation;
import mamikeji.liaowa.R;
import mamikeji.liaowa.application.MyApplication;
import mamikeji.liaowa.bean.FriendCircleBean;
import mamikeji.liaowa.bean.FriendMSGBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.activity.right.BabyDetailsActivity;
import mamikeji.liaowa.ui.activity.right.UserFollowActivity;
import mamikeji.liaowa.ui.adapter.Friend_CircleAdapter;
import mamikeji.liaowa.ui.adapter.Friend_Wa_MSGAdapter;
import mamikeji.liaowa.ui.adapter.ListViewEmptyAdapter;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.widget.ClockListView;
import mamikeji.liaowa.widget.pulltorefresh.PullToRefreshBase;
import mamikeji.liaowa.widget.pulltorefresh.PullToRefreshListView;
import mamikeji.liaowa.widget.refreshView.PtrlDownRefreshFrameLayout;

public class FriendMSGActivity extends BaseActivity {
    private static final String TAG = "FriendMSGActivity";
    private static final int TAG_CIRCLE = 1001;
    @BindView(R.id.listView_friend_msg)
    PullToRefreshListView listViewFriendMsg;
    @BindView(R.id.ptrlDownRefreshFrameLayout_friend_msg)
    PtrlDownRefreshFrameLayout ptrlDownRefreshFrameLayoutFriendMsg;
    @BindView(R.id.multiStateView_friend_msg)
    MultiStateView multiStateViewFriendMsg;

    //头部好友信息
    private SimpleDraweeView imageView_friend_headerimg;
    private TextView textView_friend_name;
    private TextView textView_friendmsg_guanzhu;
    private TextView textView_friendmsg_fans;
    private TextView textView_friendmsg_wanum;
    private ImageView imageView_friend_wa;
    private LinearLayout linearLayout_friend_wa;
    private ImageView imageView_firned_msg_header_bg;

    //娃集合
    private ClockListView listView_friend_wa;

    private View view_header, view_wa, view_circle;

    /**
     * 当前页数
     */
    private int page = 1;
    /**
     * 总页数
     */
    private int maxPage = 0;

    private FriendMSGBean bean;

    //宝妈圈数据集
    private List<FriendCircleBean.DataEntity> myfcList = new ArrayList<>();
    /**
     * 每页的活动数据集合
     */
    ArrayList<FriendCircleBean.DataEntity> mList;

    /**
     * 好友娃集合
     */
    ArrayList<FriendMSGBean.DataEntity.UserbabysEntity> waList = new ArrayList<>();

    int position_s;
    int fc_id_s;

    private Friend_Wa_MSGAdapter friend_wa_msgAdapter;
    private Friend_CircleAdapter friend_circleAdapter;

    private boolean bool_friend_wa = false;//好友娃信息

    private String friendCode;

    Boolean bool_circle_refresh;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend_msg);
        getBase();
        ButterKnife.bind(this);
        setTitleLeftImage(R.drawable.icon_fanhuibai_n_fff, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (bool_circle_refresh){
                    setResult(RESULT_OK, new Intent());
                }
                finish();
            }
        });

        friendCode = getIntent().getStringExtra(HttpKey.Friend_MSG_friendcode);

        ForLog.i("friendCode",friendCode);

        init();
        getFriendMSG();
        getMain_FriendCircleData(1, 10);

    }

    private void init() {
        bool_circle_refresh = false;
        //好友信息头部
        view_header = LayoutInflater.from(MyApplication.getContext()).inflate(R.layout.friend_layout_header, null);
        LinearLayout vp_friendmsg = new LinearLayout(this);
        vp_friendmsg.addView(view_header);//在footer的最外面再套一层LinearLayout（即footerParent）
        listViewFriendMsg.getRefreshableView().addHeaderView(vp_friendmsg, null, false);

        imageView_firned_msg_header_bg = (ImageView) view_header.findViewById(R.id.imageView_firned_msg_header_bg);
        imageView_friend_headerimg = (SimpleDraweeView) view_header.findViewById(R.id.imageView_friend_headerimg);
        textView_friend_name = (TextView) view_header.findViewById(R.id.textView_friend_name);
        textView_friendmsg_guanzhu = (TextView) view_header.findViewById(R.id.textView_friendmsg_guanzhu);
        textView_friendmsg_fans = (TextView) view_header.findViewById(R.id.textView_friendmsg_fans);
        textView_friendmsg_wanum = (TextView) view_header.findViewById(R.id.textView_friendmsg_wanum);
        imageView_friend_wa = (ImageView) view_header.findViewById(R.id.imageView_friend_wa);
        linearLayout_friend_wa = (LinearLayout) view_header.findViewById(R.id.linearLayout_friend_wa);

        imageView_friend_wa.setImageResource(bool_friend_wa ? R.drawable.icon_zhankai_h : R.drawable.icon_chushi_n);

        //娃头部
        view_wa = LayoutInflater.from(MyApplication.getContext()).inflate(R.layout.friend_layout_header_wa, null);
        LinearLayout vp_friendwa = new LinearLayout(this);
        vp_friendwa.addView(view_wa);//在footer的最外面再套一层LinearLayout（即footerParent）
        listViewFriendMsg.getRefreshableView().addHeaderView(vp_friendwa, null, false);

        listView_friend_wa = (ClockListView) view_wa.findViewById(R.id.listView_friend_wa);

        //动态标题
        view_circle = LayoutInflater.from(MyApplication.getContext()).inflate(R.layout.main_layout_header_circle, null);
        LinearLayout vp_friendcircle = new LinearLayout(this);
        vp_friendcircle.addView(view_circle);//在footer的最外面再套一层LinearLayout（即footerParent）
        listViewFriendMsg.getRefreshableView().addHeaderView(vp_friendcircle, null, false);

        friend_circleAdapter = new Friend_CircleAdapter(myfcList, this);
        listViewFriendMsg.setAdapter(friend_circleAdapter);

        listViewFriendMsg.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i >= 4) {
                    Intent intent = new Intent(FriendMSGActivity.this, CircleDetailsActivity.class);
                    intent.putExtra("fcid", myfcList.get(i - 4).getFcid() + "");
                    startActivityForResult(intent, TAG_CIRCLE);
                }
            }
        });

        multiStateViewFriendMsg.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateViewFriendMsg.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        getMain_FriendCircleData(1, 10);
                    }
                });

        ptrlDownRefreshFrameLayoutFriendMsg.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, listViewFriendMsg.getRefreshableView(), header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getFriendMSG();
                getMain_FriendCircleData(1, 10);
            }
        });

        listViewFriendMsg.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        listViewFriendMsg.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            //下拉刷新数据
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            }

            //上拉加载更多
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (++page >= maxPage) {
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            listViewFriendMsg.onRefreshComplete();
                            ForToast.showToast(R.string.error_down_end);
                        }
                    }, 1000);
                } else {
                    getMain_FriendCircleData(page, 10);
                }
            }
        });

        friend_circleAdapter.setOnItemClickListener(new Friend_CircleAdapter.OnItemClickListener() {
            @Override
            public void onZanClick(int fc_id, int position) {
                if (getJudgeLogin()){
                    getFabulousCircle(fc_id + "", position);
                }
            }
        });

        linearLayout_friend_wa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bool_friend_wa = !bool_friend_wa;
                imageView_friend_wa.setImageResource(bool_friend_wa ? R.drawable.icon_zhankai_h : R.drawable.icon_chushi_n);
                view_wa.setVisibility(bool_friend_wa ? View.VISIBLE : View.GONE);
            }
        });

        listView_friend_wa.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(FriendMSGActivity.this , BabyDetailsActivity.class);
                intent.putExtra(ForContents.WA_ID,waList.get(i).getBabyid());
                intent.putExtra(ForContents.USER_CODE , friendCode);
                startActivity(intent);
            }
        });
        textView_friendmsg_guanzhu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent mIntent = new Intent(FriendMSGActivity.this, UserFollowActivity.class);
                mIntent.putExtra(ForContents.USER_follow , friendCode);
                mIntent.putExtra("type", true);
                mIntent.putExtra(ForContents.USER_NAME, bean.getData().getNickname());
                startActivity(mIntent);
            }
        });
        textView_friendmsg_fans.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent mIntent = new Intent(FriendMSGActivity.this, UserFollowActivity.class);
                mIntent.putExtra(ForContents.USER_follow , friendCode);
                mIntent.putExtra("type", false);
                mIntent.putExtra(ForContents.USER_NAME, bean.getData().getNickname());
                startActivity(mIntent);
            }
        });
        imageView_friend_headerimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ArrayList<String> urlList = new ArrayList<>();
                urlList.add(bean.getData().getAvatar());
                Intent intent = new Intent(FriendMSGActivity.this, PreviewCircleImgActivity.class);
                intent.putStringArrayListExtra("urlList", urlList);
                intent.putExtra("position", 1);
                intent.putExtra("img_url", true);
                startActivity(intent);
            }
        });
    }

    /**
     * 获取好友信息
     */
    private void getFriendMSG() {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.Friend_MSG_usercode, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.Friend_MSG_friendcode, friendCode);
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.FRIEND_MSG, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                multiStateViewFriendMsg.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
                ptrlDownRefreshFrameLayoutFriendMsg.refreshComplete();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                ptrlDownRefreshFrameLayoutFriendMsg.refreshComplete();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        bean = new Gson().fromJson(response, FriendMSGBean.class);

                        //加载背景，
                        Glide.with(FriendMSGActivity.this)
                                .load(bean.getData().getAvatar())
                                .dontAnimate()
                                .error(R.drawable.img_baoziliaobeijing)
                                // 设置高斯模糊
                                .bitmapTransform(new BlurTransformation(FriendMSGActivity.this, 14, 2))
                                .into(imageView_firned_msg_header_bg);

                        //标题
                        setTitleName(bean.getData().getNickname());
                        if (bean.getData().getAvatar() != null){
                            imageView_friend_headerimg.setImageURI(Uri.parse(bean.getData().getAvatar()));
                        }
                        textView_friend_name.setText(bean.getData().getNickname());
                        //关注数量
                        String guanzhuString = getResources().getString(R.string.friend_msg_guanzhu);
                        String guanzhuFinal = String.format(guanzhuString, bean.getData().getFollow() + "");
                        textView_friendmsg_guanzhu.setText(guanzhuFinal);
                        //粉丝数量
                        String fansString = getResources().getString(R.string.friend_msg_fensi);
                        String fansFinal = String.format(fansString, bean.getData().getFans() + "");
                        textView_friendmsg_fans.setText(fansFinal);
                        //孩子数量
                        String numString = getResources().getString(R.string.friend_msg_wa_num);

                        String numFinal = String.format(numString, bean.getData().getUserbabys() == null ? "0":bean.getData().getUserbabys().size() + "");
                        textView_friendmsg_wanum.setText(numFinal);
                        //判断是否当前登录用户
                        if (!ForPreference.getString(ForContents.USER_CODE).equals(friendCode)){
                            switch (bean.getData().getIsfollow()) {
                                case 1:
                                    setTitleRightBtn(R.string.momcircle_guanzhu_1, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            if(getJudgeLogin()){
                                                getFriendFollow();
                                            }
                                        }
                                    });
                                    break;
                                case 2:
                                    setTitleRightBtn(R.string.momcircle_guanzhu_2, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            if(getJudgeLogin()){
                                                getFriendFollow();
                                            }
                                        }
                                    });
                                    break;
                                case 3:
                                    setTitleRightBtn(R.string.momcircle_guanzhu_3, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            if(getJudgeLogin()){
                                                getFriendFollow();
                                            }
                                        }
                                    });
                                    break;
                            }
                        }
                        /**
                         * 判断是否有娃
                         */
                        if (bean.getData().getUserbabys().size() > 0) {
                            view_wa.setVisibility(View.GONE);
                            waList.clear();
                            waList.addAll(bean.getData().getUserbabys());
                            friend_wa_msgAdapter = new Friend_Wa_MSGAdapter(waList, FriendMSGActivity.this);
                            listView_friend_wa.setAdapter(friend_wa_msgAdapter);

                            ViewGroup.LayoutParams params = listView_friend_wa.getLayoutParams();
                            params.height = 200*bean.getData().getUserbabys().size();
                            listView_friend_wa.setLayoutParams(params);
                        } else {
                            view_wa.setVisibility(View.GONE);
                        }
                        multiStateViewFriendMsg.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                    } else {
                        multiStateViewFriendMsg.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 获取朋友圈信息
     *
     * @param index
     * @param size
     */
    private void getMain_FriendCircleData(int index, int size) {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.FC_INDEXPAGE, index + "");
        formMap.put(HttpKey.FC_PAGESIZE, size + "");
        formMap.put(HttpKey.FC_TYPE, "1");
        formMap.put(HttpKey.FC_USERCODE, friendCode);
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.FRIEND_MY_CIRCLE_DATE, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                listViewFriendMsg.onRefreshComplete();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                listViewFriendMsg.onRefreshComplete();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        FriendCircleBean bean = new Gson().fromJson(response, FriendCircleBean.class);
                        if (bean.getData().size() > 0) {
                            mList = new ArrayList<FriendCircleBean.DataEntity>();
                            mList = (ArrayList<FriendCircleBean.DataEntity>) bean.getData();

                            if (page == 1) {
                                maxPage = bean.getTotal();
                                myfcList.clear();
                                myfcList.addAll(mList);
                                friend_circleAdapter.setList(myfcList);
                            } else {
                                myfcList.addAll(mList);
                                friend_circleAdapter.notifyDataSetChanged();
                            }
                        } else {
                            if (page == 1)
                                listViewFriendMsg.setAdapter(new ListViewEmptyAdapter(FriendMSGActivity.this , "空空如也~~~"));
                        }
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 关注
     */
    private void getFriendFollow() {
        showLoading();
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.Friend_MSG_usercode, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.Friend_Follow_friendcode, friendCode);
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.FRIEND_MSG_follow, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG,response);
                hideLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        int follow = ForPreference.getInt(ForContents.USER_follow);//关注数
                        int num = jsonObject.getInt("data");
                        switch (num) {
                            case 1:
                                ForPreference.putInt(ForContents.USER_follow , ++follow);
                                setTitleRightBtn(R.string.momcircle_guanzhu_1 , null);
                                break;
                            case 2:
                                ForPreference.putInt(ForContents.USER_follow , --follow);
                                setTitleRightBtn(R.string.momcircle_guanzhu_2 , null);
                                break;
                            case 3:
                                ForPreference.putInt(ForContents.USER_follow , ++follow);
                                setTitleRightBtn(R.string.momcircle_guanzhu_3 , null);
                                break;
                        }
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 点赞
     */
    private void getFabulousCircle(final String fcid, final int position) {
        showLoading();
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.FC_PRAISE_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.FC_PRAISE_FCID, fcid);
        formMap.put(HttpKey.FC_PRAISE_TYPE, "2");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.FRIEND_CIRCLE_PRAISE, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                hideLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        bool_circle_refresh = true;
                        int num = myfcList.get(position).getPraisenumber();
                        if (myfcList.get(position).getPraisestate() == 1) {
                            myfcList.get(position).setPraisestate(0);
                            myfcList.get(position).setPraisenumber(--num);
                        } else {
                            myfcList.get(position).setPraisestate(1);
                            myfcList.get(position).setPraisenumber(++num);
                        }
                        friend_circleAdapter.notifyDataSetChanged();
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == TAG_CIRCLE) {
                //获取朋友圈
                bool_circle_refresh = true;
                getMain_FriendCircleData(1, 10);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if(bool_circle_refresh){
                setResult(RESULT_OK, new Intent());
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
